﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace QWManage.Logs
{
    public enum LogLevel
    {
        Info,
        Warning,
        Error
    }

    public class LogMgr
    {
        private static object _lockObj = new object();

        public static void Log(Exception ex)
        {
            Log(ex.Message, ex.ToString(), LogLevel.Error);
        }

        public static void Log(string caption, string message, LogLevel logLevel = LogLevel.Info)
        {
            try
            {
                lock (_lockObj)
                {
                    message = Regex.Replace(message, "\r\n", "</br>");
                    message = Regex.Replace(message, "\r", "</br>");
                    message = Regex.Replace(message, "\n", "</br>");
                    string logPath = Path.Combine(Application.StartupPath, "日志");
                    if (!Directory.Exists(logPath)) Directory.CreateDirectory(logPath);
                    string fn = Path.Combine(logPath, DateTime.Now.Date.ToString("yyyyMMdd") + ".txt");
                    using (FileStream fs = new FileStream(fn, FileMode.Append))
                    {
                        using (StreamWriter sw = new StreamWriter(fs))
                        {
                            string line = DateTime.Now.ToString("HH:mm:ss") + "\t" + logLevel.ToString() + "\t" + caption + "\t" + message;
                            //开始写入
                            sw.WriteLine(line);
                            //清空缓冲区
                            sw.Flush();
                            //关闭流
                        }
                    }
                }
            }
            catch { }
        }
    }
}
